package cn.ty.znsz.index;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;

import cn.ty.znsz.common.model.SysMenu;
import cn.ty.znsz.common.utils.CommonUtils;

public class IndexService {
	
	private SysMenu menuDao=new SysMenu().dao();
	
	/**
	 * 获取菜单列表
	 */
	public Ret getMenus(String token) {
		//得到用户所属的角色
		String key=Redis.use().get(token);
		String roleIds=Redis.use().hget(key, "roleIds");
		List<Record> list=Db.find("SELECT DISTINCT(b.pmenuIds) from sys_role_point a LEFT JOIN sys_menu_point b ON a.pointId=b.id WHERE a.roleId IN ("+roleIds+");");
		Set<String> set = new HashSet<>();
		for(int i=0;i<list.size();i++) {
			String ids=list.get(i).get("pmenuIds");
			String[] b=ids.split("\\.");
		    for(String str:b) {
		    	set.add(str);
		    }
		}		
		String result = String.join(",", set);
		List<SysMenu> allMenus=menuDao.find("SELECT a.id,a.title,a.code,a.icon,CONCAT(a.href,'?id=',a.id) href,a.parentId,false spread from sys_menu a "
				+ "WHERE a.isShow=1 and a.id in ("+result+") ORDER BY a.sortOrder;");
		List<SysMenu> rootMenus=new ArrayList<SysMenu>();
//		List<SysMenu> rootMenus2=new ArrayList<SysMenu>();
		for(SysMenu sm:allMenus) {
			if(sm.getParentId()==0) {
//				if(sm.getCode().equals("teacher")) {
					rootMenus.add(sm);
//				}else if(sm.getCode().equals("system")) {
//					rootMenus2.add(sm);
//				}
			}
		}
		//为根菜单设置子菜单，getClild是递归调用的
		for(SysMenu sm:rootMenus) {
			/* 获取根节点下的所有子节点 使用getChild方法*/
	        List<SysMenu> childList = CommonUtils.getChild(sm.getId(), allMenus);
	        sm.put("children", childList);//给根节点设置子节点
		}
//		for(SysMenu sm:rootMenus2) {
//			/* 获取根节点下的所有子节点 使用getChild方法*/
//	        List<SysMenu> childList = CommonUtils.getChild(sm.getId(), allMenus);
//	        sm.put("children", childList);//给根节点设置子节点
//		}
		return Ret.create().set("data", rootMenus);
	}

}
